%%% -------------------------------------------------------------------
%%% Author  : tangj
%%% Description :
%%%
%%% Created : 2012-9-22
%%% -------------------------------------------------------------------
-module(gateway_acceptor).
-behavior(gen_server).

-export([
		 start_link/1,
		 get_socket_data/1
		]).

%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, 
		 terminate/2, code_change/3]).

-record(state, {sock}).

%% --------------------------------------------------------------------

start_link(LSock) ->
	gen_server:start_link(?MODULE, LSock, []).

%% --------------------------------------------------------------------

init(LSock) ->
	io:format("gateway_acceptor~p init~n", [self()]),
	gen_server:cast(self(), accept),
	{ok, #state{sock=LSock}}.
							   
handle_call(_Request, _From, State) -> 
	{reply, ok, State}.

handle_cast(accept, State) ->
	case gen_tcp:accept(State#state.sock) of
		{ok, Socket} -> 
			Pid = spawn(?MODULE, get_socket_data, [Socket]),
			gen_tcp:controlling_process(Socket, Pid),
			gen_server:cast(self(), accept),
			{noreply, State};
		Error -> 
			{stop, {cannot_accept, Error}, State}
	end;

handle_cast(_Msg, State) ->
    {noreply, State}.

handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
	ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

%% --------------------------------------------------------------------
%% 接收数据进程
get_socket_data(Socket) ->
	case gen_tcp:recv(Socket, 0, infinity) of
		{ok, Binary} ->
			io:format("~p~n", [Binary]),
			get_socket_data(Socket);
		{error, closed} ->
			ok
	end.

